package com.chunayev.numerology.gui.table.listener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPopupMenu;

import com.chunayev.numerology.gui.table.NameCalculationsTable;


/**
 * @author Sergey Chunayev
 */
public class TokensMenuInvoker extends MouseAdapter {
    
    private JPopupMenu popupMenu;
    
    /**
     * 
     */
    public TokensMenuInvoker() {
        super();
    }
    
    /**
     * @param popupMenu
     */
    public TokensMenuInvoker(final JPopupMenu popupMenu) {
        super();
        this.popupMenu = popupMenu;
    }
    
    /**
     * @return the popupMenu
     */
    public JPopupMenu getPopupMenu() {
        return this.popupMenu;
    }
    
    /*
     * (non-Javadoc)
     * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
     */
    @Override
    public void mousePressed(final MouseEvent e) {
        super.mousePressed(e);
        showPopup(e);
    }
    
    /*
     * (non-Javadoc)
     * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
     */
    @Override
    public void mouseReleased(final MouseEvent e) {
        super.mouseReleased(e);
        showPopup(e);
    }
    
    /**
     * @param popupMenu
     *            the popupMenu to set
     */
    public void setPopupMenu(final JPopupMenu popupMenu) {
        this.popupMenu = popupMenu;
    }
    
    private void showPopup(final MouseEvent e) {
        if (e.isPopupTrigger() && popupMenu != null) {
            NameCalculationsTable table = (NameCalculationsTable) e
                    .getComponent();
            table.getSelectionModel().setSelectionInterval(0,
                    table.rowAtPoint(e.getPoint()));
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
}
